import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Dialog, Drawer, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { column, ENUMS } from './stores/definitions';
import { toJS } from 'mobx';
import DataForm from './components/DataForm';

const tableId = uniqueId('tauTable-');

const Rule = () => {
  const [modal, setModal] = useState({
    show: null,
    record: null,
  });
  const [state, setState] = useState([]);
  const groupRef = useRef(null);
  const [idx, setIdx] = useState(-1);
  const { ruleStore: store } = useStore();

  useEffect(() => {
    (async () => {
      const res = await store.getId(store._group_id);
      groupRef.current = res;
      const { noticeRules = [] } = res;
      store._pageData = noticeRules;
      setState(noticeRules);
    })();
  }, [store._group_id, store.data]);

  const handleAddMember = () => {
    if (!store._group_id) {
      Message.warning({ content: t`请选择管理群！`, duration: 7000 });
      return;
    }
    setModal({ show: 'add', record: null });
  };

  const handleOnEdit = (r, index) => {
    setModal({ show: 'edit', record: r, index });
    setIdx(index);
  };

  const handleCancel = () => {
    setModal({ show: null, record: null });
  };

  const handleRemove = (index) => {
    Dialog.confirm({
      content: t`确定删除吗？`,
      onOk: async () => {
        try {
          const { noticeRules } = _.cloneDeep(groupRef.current);
          const removeData = noticeRules.filter((p, i) => i !== index);
          const params = {
            ...groupRef.current,
            noticeRules: removeData,
          };
          await store.update(params);
          Message.success({ content: t`删除成功` });
        } catch (e) {
          Message.error({ content: t`删除失败`, duration: 7000 });
          throw e;
        }
      },
    });
  };

  const handelOnSubmit = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        const { noticeRules } = _.cloneDeep(groupRef.current);
        const params = {
          ...groupRef.current,
          noticeRules: [...noticeRules, { ...toJS(result) }],
        };
        await store.update(params);
        Message.success({ content: t`添加成功` });
      } catch (e) {
        Message.error({ content: t`添加失败`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  const handelOnUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        const { noticeRules } = _.cloneDeep(groupRef.current);
        noticeRules[idx] = { ...toJS(result) };
        const params = {
          ...groupRef.current,
          noticeRules,
        };
        await store.update(params);
        Message.success({ content: t`添加成功` });
      } catch (e) {
        Message.error({ content: t`添加失败`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        // onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-member',
            title: t`添加规则`,
            type: 'primary',
            onClick: handleAddMember,
          },
        ]}
        keywordSearch={{
          enabled: false,
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={state}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('batchId', { width: 100 }),
            column('startPoint', { width: 100 }),
            column('endPoint', { width: 100 }),
            {
              title: t`操作`,
              dataIndex: 'ruleNumber',
              width: 100,
              cell: (_, i, r) => (
                <>
                  <Button text type="primary" onClick={() => handleOnEdit(r, i)} >{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" style={{ color: 'red' }} onClick={() => handleRemove(i)} >{t`删除`}</Button>
                </>),
            },
          ]}
        />
      </div>
      <Drawer
        visible={modal.show === 'add' || modal.show === 'view' || modal.show === 'edit'}
        title={ENUMS._TITLE_TEXT[modal.show]}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal({ ...modal, toClose: `toClose$${Date.now()}` })}
        width="600px"
      >
        <DataForm
          state={state}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal.show === 'add' ? handelOnSubmit : handelOnUpdate}
        />
      </Drawer>
    </TauPage>
  );
};

export default observer(Rule);
